local desc_1v1 = [[
  # 璀璨宝石模式

  该模式下，玩家通过收集精灵球和宝可梦来获得分数。每个回合，玩家可以选择以下行动之一：
  1. 拿取3种不同的精灵球。
  2. 拿取2种相同精灵球（如果该颜色宝石数量不少于4）。
  3. 购买一张宝可梦并将其放入自己的牌库。
  4. 保留一张宝可梦并获得一个大师球（大师球可以当做任意其余精灵球）。

  当玩家购买一张牌时，他们获得该牌上的分数和特殊宝石。游戏结束时，分数最高的玩家获胜。
]]
local GameEvent=require "packages/jbs2/pokgame/pokegems_flow"

local pokepool=require "packages/jbs2/pokgame/pokemonlist"
--local pvetool = require("packages.jbs.record.PVETool")




--
--技能获得
local function execGameEvent(type, ...)
  local event = GameEvent:new(type, ...)
  local _, ret = event:exec()
  return ret
end



local s1v1_getLogic = function()
  local m_1v1_logic = GameLogic:subclass("jbspekegems_logic")
  function m_1v1_logic:prepareForStart()
    local room = self.room
    local players = room.players

    self:addTriggerSkill(GameRule)
    for _, trig in ipairs(Fk.global_trigger) do
      if trig.name ~= "mobile_effect" then  --关闭手杀特效
        self:addTriggerSkill(trig)
      end
    end
    self.room:sendLog{ type = "$GameStart" }
  end

  
  function m_1v1_logic:run()
    -- default logic
    local room = self.room
    table.shuffle(self.room.players)
    self:assignRoles()
    self.room.game_started = true
    room:doBroadcastNotify("StartGame", "")
    room:adjustSeats()
    --[[ 因为未完工，在release版暂时不启用。
    for _, p in ipairs(room.players) do
      p.ai = SmartAI:new(p)
    end
    --]]
    self:chooseGenerals()
    self:prepareDrawPile()
    self:buildPlayerCircle()
    self:broadcastGeneral()
    self:attachSkillToPlayers()
    self:prepareForStart()
    self:action()
  end
  function m_1v1_logic:action()
    self:trigger(fk.GamePrepared)
    local room = self.room
    --execGameEvent(GameEvent.UnoDrawInitial)
    while true do
      execGameEvent(GameEvent.PokeGemsRound)
      if room.game_finished then break end
    end
  end

  function m_1v1_logic:prepareDrawPile()
    local room = self.room
    local allCardIds = Fk:getAllCardIds()
    --重新过滤卡组
    local filterCardIds = {}
    local while_cards = {"standard","standard_cards","maneuvering","jbsuno_cards"}
    local blacklist = { "amazing_grace"}
    for i = #allCardIds, 1, -1 do
      local id = allCardIds[i]
      local card = Fk:getCardById(id)
      if card then
        if card.is_derived or not table.contains(while_cards,card.package.name) or table.contains(blacklist, card.name) then
          table.removeOne(allCardIds, id)
          table.insert(room.void, id)
          room:setCardArea(id, Card.Void, nil)
        end
      if table.contains(while_cards,card.package.name) and not table.contains(blacklist, card.name)  then
        if not card.is_derived then
          table.insert(filterCardIds,id)
        end
      end
    end
    end
     
  
  

    local seed = math.random(2 << 32 - 1)
    table.shuffle(filterCardIds,seed)
    room.draw_pile = filterCardIds
    for _, id in ipairs(room.draw_pile) do
      room:setCardArea(id, Card.DrawPile, nil)
    end
    room:doBroadcastNotify("PrepareDrawPile", seed)
  end

  function m_1v1_logic:chooseGenerals()
    local room = self.room ---@type Room
    room:doBroadcastNotify("ShowToast", Fk:translate("#BrawlInitialNotice"))
    for _, p in ipairs(room.players) do
      room:setPlayerProperty(p, "role_shown", true)
      room:broadcastProperty(p, "role")
    end
  
    local lord = room:getLord()
    room.current = lord
    local players = room.players

    room.gems_tool =nil
    room.pool={}
    room.gems_tool=pokepool:new()
    room.gems_tool:initData()
    
    room.pool=room.gems_tool:startdraw()--商店池子

    for k, p in ipairs(players) do
      local avatar = p._splayer:getAvatar()
      if avatar == "anjiang" then avatar = table.random{ "blank_shibing", "blank_nvshibing" } end
      local avatar_general = Fk.generals[avatar] or Fk.generals["mouxusheng"]
      room:setPlayerGeneral(p, avatar_general.name, true)
      room:broadcastProperty(p, "general")
      room:setPlayerProperty(p, "shield", 0)
      room:setPlayerProperty(p, "maxHp", p.role == "lord" and 5 or 4)
      room:setPlayerProperty(p, "hp", p.role == "lord" and 5 or 4)

    end

    --[[ 鸽！直接用头像，我写在最前面
    for _, p in ipairs(players) do
      local genders = {"male", "female"}
      local data = json.encode({ genders, genders, "AskForGender", "#ChooseGender" })
      p.request_data = data
      p.default_reply = table.random(genders)
    end

    room:notifyMoveFocus(players, "AskForGender")
    room:doBroadcastRequest("AskForChoice", players)

    for _, p in ipairs(players) do
      local genderChosen
      if p.reply_ready then
        genderChosen = p.client_reply
      else
        genderChosen = p.default_reply
      end
      room:setPlayerGeneral(p, genderChosen == "male" and "blank_shibing" or "blank_nvshibing", true, true)
      p.default_reply = ""
    end
    --]]
  end

  function m_1v1_logic:broadcastGeneral()
    return
  end
  function m_1v1_logic:attachSkillToPlayers()
    local room = self.room
    room.total_gems={6,6,6,6,6,5}
    --room:doBroadcastNotify("ShowToast", Fk:translate("#BrawlInitialNotice"))
    for _, p in ipairs(room.alive_players) do
      p.buff_table={0,0,0,0,0,0}
      p.owned_cards={}
      local gemlist={0,0,0,0,0,1}
      local cardslist=p.owned_cards or {}
      pokepool:updateplayergems(p, gemlist,cardslist)
      
    end
  end
  return m_1v1_logic
end

local m_1v1_rule = fk.CreateTriggerSkill{
  name = "#jbspokegems_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart,fk.GameOverJudge},
  can_refresh = function(self, event, target, player, data)
    if event==fk.AfterCardsMove then
      if not player:isKongcheng() then return end
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand then
            return true
          end
        end
      end
    end
    else
      return target == player
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
    room:setBanner("@[:]jbsfire_rule","jbspokegems-intro")
    player.room:setTag("pokegems_end",false)
    elseif event == fk.GameOverJudge then
      local body = room:getPlayerById(data.who)
      local target=body
      for _, p in ipairs(room.players) do
        if p.rest>target.rest then
          target=p
        end
      end

      room:setTag("SkipGameRule", true)
      room:gameOver(target.role)

   
      

    end
  end,
}



Fk:addQmlMark{
  name = "jbspoke_gems",
  qml_path = "packages/jbs2/qml/playerballs",
  how_to_show = function(name, value, p)
    -- FIXME: 神秘bug导致value可能为空串有待排查
    return " "
  end,
 
}

Fk:addMiniGame{
 name = "pokemongems_sel",
 qml_path = "packages/jbs2/qml/Shopshow",
 default_choice = function(player, data)
  return {}
end,
update_func = function(player, data)
  local room = player.room
  if #data == 1 and data[1] == "confirm" then
    for _, p in ipairs(room:getOtherPlayers(player, false)) do
      p:doNotify("UpdateMiniGame", "")
    end
  end
end,
}



local m_1v1_mode = fk.CreateGameMode{
  name = "jbspokegems_mode",
  minPlayer = 2,
  maxPlayer =8,
  rule = m_1v1_rule,
  logic = s1v1_getLogic,
  surrender_func = function(self, playedTime)
    return { { text = "time limitation: 2 min", passed = playedTime >= 120 } }
  end,
}
-- extension:addGameMode(m_1v1_mode)
Fk:loadTranslationTable{
  ["jbspokegems_mode"] = "璀璨宝石",
  [":jbspokegems_mode"] = desc_1v1,
  ["@jbspokegems_assignment"]="任务",
  ["jbspokegems-intro"]="璀璨宝石",
  [":jbspokegems-intro"]=[[该模式下，玩家通过收集精灵球和宝可梦来获得分数。每个回合，玩家可以选择以下行动之一：
  <br>1. 拿取3种不同的精灵球。<br>

  <br>2. 拿取2种相同精灵球（如果该颜色宝石数量不少于4）。<br>

  <br>3. 购买一张宝可梦并将其放入自己的牌库。<br>

  <br>4. 预定一张宝可梦并获得一个大师球（大师球可以当做任意其余精灵球）。(未实装，目前开局固定获得一个大师球)

  <br><br>当玩家购买一张牌时，他们获得该牌上的分数和特殊宝石。率先得到18分的玩家获胜。
  <br><br>宝可梦对应的特色宝石在购买宝可梦是可抵消对应颜色的宝石。<br>例如：玩家拥有有一个普通球的宝可梦，购买其他宝可梦时，
  可以少支付一个普通球。]],
  ["#jbspokegems_rule"]="璀璨宝石",
  ["#pokegems-choicewild"]="选择一个花色，下家开始须打出此花色",
  ["@pokegems-score"]="得分",
  ["jbspoke_gems"]="宝石",
  ["@[jbspoke_gems]"]="宝石信息",
  ["@@pokegems_end"]="最终轮",
  ["pokemongems_sel"]="璀璨宝石",

}

return m_1v1_mode